//
//  BKOAuthViewController.swift
//  微博
//
//  Created by mac on 16/8/10.
//  Copyright © 2016年 xbk. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

//微博AppKey
let WeiAppkey = "1670902533"
//微博AppSecret
let WeiboAppSecret = "d17afb6b50dabbdada3d5460ee2456bb"
//授权回调页
let weiboRedirect_Uri = "http://www.gov.cn"


class BKOAuthViewController: UIViewController {
    
    
    private lazy var webViwe :UIWebView = UIWebView()
    
    override func loadView() {
        
        //修改透明度
        webViwe.opaque = false
        
        view = webViwe
        
        //设置webView的代理
        webViwe.delegate = self
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setNavUI()
        requestOAuthLogin()
    }

    //为导航条添加按钮
    private func setNavUI() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillAction")
        navigationItem.title = "微博登录"
    }
    
    @objc private func cancelAction () {
    
       // print("取消")
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
     @objc private func autoFillAction () {
    
        //print("自动填充")
        webViwe.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'wangyixiaoqing@126.com';document.getElementById('passwd').value = 'IOSdevelop'")
    }


    //  MARK: --  请求第三方登录的页面
    private func requestOAuthLogin () {
    
//        https://api.weibo.com/oauth2/authorize?client_id=1670902533&redirect_uri=http://www.gov.cn
        
        //准备url
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiAppkey)&redirect_uri=\(weiboRedirect_Uri)"
        //准备urlRequest
        let urlRequest = NSURLRequest(URL:NSURL(string: url)!)
        
        //print(url)
        
        //通过webView加载页面
        webViwe.loadRequest(urlRequest)
        
    }
    
}


    //  MARK: --  webView代理 获取code
extension BKOAuthViewController :UIWebViewDelegate{

    //将要加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //获取绝对地址
        // 绝对地址:"http://www.gov.cn/?code=50052f8d9cb16480311125d44d27154b"
        print(request.URL?.absoluteString)
        
        
        //因为URL是一个可选类型,所以判断
        guard let url = request.URL else{
        
            return false
        }
        
        //如果不以回调页开头,不需要关心    prefix 前缀
        if !url.absoluteString.hasPrefix(weiboRedirect_Uri){
        
            return true
        }
        
         //  MARK: -- 获取code
        // query 是获取?后的值
        if let query = url.query where query.hasPrefix("code="){
        
            print("-----"+query)
            //获取code
            let code = query.substringFromIndex("code=".endIndex)
            print("++++++"+code)
            
            BKUserAccountViewModel.shareUserAccount.requestAccessTokenWithCode(code, callBack: { (isSuccess) -> () in
                
                if isSuccess{
                
                    print("登录成功")
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        
                        //发送通知切换根视图控制器
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification,object :self)
                    })
                }else{
                
                    print("登录失败")
                }
            })
            
        }else{
        
            dismissViewControllerAnimated(true, completion: nil)
        }
        
        
        return false
    }
    
    //  开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    //  加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //  加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}


